<template>
  <div class="app-container">
    <SearchContent :queryParams="queryParams" @query="handleQuery" @reset="resetQuery">
      <el-col :span="6">
        <el-form-item label="品牌:" prop="brandId">
          <el-select v-model="queryParams.brandId" clearable filterable style="width: 100%" @change="getSeriesName">
            <template v-for="dict in brandList">
              <el-option :label="dict.name" :value="dict.id" :key="dict.id"></el-option>
            </template>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="车系:" prop="seriesId">
          <el-select v-model="queryParams.seriesId" clearable filterable style="width: 100%" @change="getModelName">
            <template v-for="dict in seriesList">
              <el-option :label="dict.name" :value="dict.id" :key="dict.id"></el-option>
            </template>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="车型:" prop="modelId">
          <el-select v-model="queryParams.modelId" filterable style="width: 100%" clearable>
            <template v-for="dict in carIdList">
              <el-option :label="dict.name" :value="dict.id" :key="dict.id"></el-option>
            </template>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="维保项目:" prop="maintenanceItemId">
          <el-select v-model="queryParams.maintenanceItemId" clearable>
            <template v-for="dict in dict.type.main_tenance_item">
              <el-option :label="dict.label" :value="dict.value" :key="dict.value"></el-option>
            </template>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="能源类型:" prop="energyType">
          <el-select v-model="queryParams.energyType" clearable>
            <template v-for="dict in dict.type.energy_type">
              <el-option :label="dict.label" :value="dict.value" :key="dict.value"></el-option>
            </template>
          </el-select>
        </el-form-item>
      </el-col>
    </SearchContent>

    <div class="card-wrap card-padding">
      <div class="table-title-wrap justify-end">
        <el-button type="primary" size="mini" @click="handleAdd" v-hasPermi="['synthesis:maintenance:add']">新增</el-button>
        <el-button type="primary" size="mini" @click="bHandleAdd" v-hasPermi="['synthesis:maintenance:batchAdd']">批量新增</el-button>
      </div>

      <table-page :loading="loading" :dataList="dataList" border :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @setSizeCurrent="getList">
        <!-- 操作插槽 -->
        <template slot="tableColAc">
          <el-table-column label="操作" width="150" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <e-button v-hasPermi="['synthesis:maintenance:edit']" size="mini" type="text" @click="handleUpdate(scope.row)">编辑 </e-button>
              <el-button v-hasPermi="['synthesis:maintenance:void']" type="text" @click="voids(scope.row)">作废</el-button>
            </template>
          </el-table-column>
        </template>
        <!-- 普通列插槽 -->
        <template slot="tableCol">
          <el-table-column label="车型" align="center" prop="modelName" />
          <el-table-column label="能源类型" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.energyType == 0 ? '燃油' : '新能源' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="排量(L)" align="center" prop="liter" />
          <el-table-column label="维保项目" align="center" prop="maintenanceItemName" />
          <el-table-column label="单次费用(元)" align="center" prop="baseFee">
            <template slot-scope="scope">
              <span>{{ scope.row.baseFee }}</span>
            </template>
          </el-table-column>
        </template>
      </table-page>
    </div>

    <!-- 添加或修改测试单表对话框 -->
    <el-dialog :title="title" :visible.sync="open" append-to-body class="form-dialog" width="35%">
      <div style="width: 60%; margin: 0 auto">
        <el-form ref="form" :model="form" label-width="120px" :rules="rules">
          <el-form-item label="车型:" class="is-required">
            <el-input style="width: 100%" v-model="modelNameDig" readonly @focus="digCarVehicleType"></el-input>
          </el-form-item>
          <el-form-item label="维保项目:" prop="maintenanceItemId">
            <el-select v-model="form.maintenanceItemId" clearable style="width: 100%">
              <template v-for="dict in dict.type.main_tenance_item">
                <el-option :label="dict.label" :value="dict.value" :key="dict.value"></el-option>
              </template>
            </el-select>
          </el-form-item>
          <el-form-item label="单次费用:" prop="baseFee">
            <el-input style="width: 100%" v-model="form.baseFee" clearable maxlength="13" @input="form.baseFee = form.baseFee.replace(/^\D*([0-9]\d*\.?\d{0,2})?.*$/, '$1')"></el-input>
          </el-form-item>
        </el-form>
      </div>

      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button @click="cancel">取消</el-button>
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 认</el-button>
      </div>
    </el-dialog>

    <el-dialog title="选择车型" :visible.sync="openDig" append-to-body class="form-dialog" width="55%">
      <SearchContent :queryParams="queryParamsDig" @query="handleQueryDig" @reset="resetQueryDig">
        <el-form :model="queryParamsDig" label-width="50px">
          <el-col :span="6">
            <el-form-item label="品牌:">
              <el-select v-model="queryParamsDig.carBrandId" filterable clearable style="width: 100%" @change="getSeriesNameDig">
                <el-option v-for="dict in brandListDig" :label="dict.name" :value="dict.id" :key="dict.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="车系:">
              <el-select v-model="queryParamsDig.carSeriesId" clearable filterable style="width: 100%" @change="getModelNameDig">
                <el-option v-for="dict in seriesListDig" :label="dict.name" :value="dict.id" :key="dict.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="车型:">
              <el-select v-model="queryParamsDig.Id" filterable clearable style="width: 100%">
                <el-option v-for="dict in carIdListDig" :label="dict.name" :value="dict.id" :key="dict.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-form>
      </SearchContent>
      <el-row>
        <table-page :maxHeight="300" :loading="loadingDig" :dataList="dataListDig" border :total="totalDig" :page.sync="queryParamsDig.pageNum" :limit.sync="queryParamsDig.pageSize" @setSizeCurrent="getListDig">
          <!-- 普通列插槽 -->
          <template slot="tableCol">
            <el-table-column label="" align="center" width="35">
              <template scope="scope">
                <el-radio :label="scope.row.id" v-model="radio" @change.native="getCurrentRow(scope.row)">{{ }}</el-radio>
              </template>
            </el-table-column>
            <el-table-column label="品牌" align="center" prop="brandName" />
            <el-table-column label="车系" align="center" prop="seriesName" />
            <el-table-column label="车型" align="center" prop="modelName" />
          </template>
        </table-page>
      </el-row>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button @click="closeDig">取 消</el-button>
        <el-button type="primary" @click="submitDig">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import SearchContent from '@/components/SearchContent/index.vue'
import { getCarModelList, carModelAdd, carModelDetail, carModelDelete, carModelUpdate, getListDig, MAINTENANCEFE, TEMPLATEDRIVER } from '@/api/globalField'
import { getBrandNames, getSeriesName, getModelName } from '@/api/system/linkageSelect.js'
import LinkageSelect from '../../../components/linkageSelect'
export default {
  name: 'Detail',

  components: {
    SearchContent,
    LinkageSelect,
  },
  dicts: ['business_scope', 'main_tenance_item', 'energy_type', 'dis_pla_ce_ment'],
  data() {
    return {
      brandList: [],
      seriesList: [],
      carIdList: [],
      queryParamsDig: {
        pageNum: 1,
        pageSize: 10,
      },
      openDig: false,
      loadingDig: false,
      dataListDig: [],
      totalDig: 0,
      //按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      total: 0,
      dataList: [],
      // 表单参数
      form: {},
      rules: {
        // modelId: [{ required: true, message: '请选择车型', trigger: 'change' }],
        maintenanceItemId: [{ required: true, message: '请选择维保项目', trigger: 'change' }],
        baseFee: [{ required: true, message: '请输入单次费用', trigger: 'change' }],
      },
      brandListDig: [],
      seriesListDig: [],
      carIdListDig: [],
      radio: '',
      modelName: '',
      modelNameDig: '',
    }
  },
  created() {
    this.getList()
    this.getBrandNames()
  },
  methods: {
    getCurrentRow(row) {
      // 获取选中数据 row表示选中这一行的数据，可以从里面提取所需要的值
      console.log(row.modelName, '-------')
      this.modelName = row.modelName
    },
    handleQueryDig() {
      this.getListDig()
    },
    resetQueryDig() {
      this.queryParamsDig = {
        pageNum: 1,
        pageSize: 10,
      }
      this.seriesListDig = []
      this.carIdListDig = []
      this.getListDig()
    },
    // 获取品牌
    getBrandNames() {
      getBrandNames({ brandName: '' }).then((res) => {
        this.brandListDig = res
        this.brandList = res
      })
    },
    // 获取车系
    getSeriesName() {
      if (this.queryParams.brandId) {
        getSeriesName(this.queryParams.brandId).then((res) => {
          this.seriesList = res
          this.$set(this.queryParams, 'seriesId', '')
          this.$set(this.queryParams, 'modelId', '')
        })
      } else {
        this.seriesList = []
        this.carIdList = []
        this.$set(this.queryParams, 'seriesId', '')
        this.$set(this.queryParams, 'modelId', '')
      }
    },
    // 获取车型
    getModelName() {
      if (this.queryParams.seriesId) {
        getModelName(this.queryParams.seriesId).then((res) => {
          this.carIdList = res
          this.$set(this.queryParams, 'modelId', '')
        })
      } else {
        this.carIdList = []
        this.$set(this.queryParams, 'modelId', '')
      }
    },
    // 获取车系
    getSeriesNameDig() {
      if (this.queryParamsDig.carBrandId) {
        getSeriesName(this.queryParamsDig.carBrandId).then((res) => {
          this.seriesListDig = res
          this.$set(this.queryParamsDig, 'carSeriesId', '')
          this.$set(this.queryParamsDig, 'Id', '')
        })
      } else {
        this.seriesListDig = []
        this.carIdListDig = []
        this.$set(this.queryParamsDig, 'carSeriesId', '')
        this.$set(this.queryParamsDig, 'Id', '')
      }
    },
    // 获取车型
    getModelNameDig() {
      if (this.queryParamsDig?.carSeriesId) {
        getModelName(this.queryParamsDig?.carSeriesId).then((res) => {
          this.carIdListDig = res
          this.$set(this.queryParamsDig, 'Id', '')
        })
      } else {
        this.carIdListDig = []
        this.$set(this.queryParamsDig, 'Id', '')
      }
    },
    digCarVehicleType() {
      this.openDig = true
      this.queryParamsDig = {
        pageNum: 1,
        pageSize: 10,
      }
      this.getListDig()
    },
    linkageChange(val) {
      this.modelId = val
    },
    /** 批量新增操作 */
    bHandleAdd() {
      this.$UploadDialog({
        title: '维保费分项明细',
        showtoastSureBtn: false,
        showResult: false,
        uploadConfig: {
          uploadFileUrl: `#${MAINTENANCEFE}`,
          limit: 10,
          params: {},
          fileType: ['xls', 'xlsx'],
          templateUrl: `${TEMPLATEDRIVER('carModelMaintenanceFeeBase')}`,
          templateName: `维保费分项明细-导入模版.xlsx`,
        },
      })
        .then((res) => {
          this.handleQuery()
        })
        .catch((err) => {
          this.handleQuery()
        })
    },
    voids(row) {
      this.$confirm('确认作废?', '作废', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          carModelDelete(row.id).then((res) => {
            this.$message({
              type: 'success',
              message: '作废成功!',
            })
            this.getList()
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消作废',
          })
        })
    },
    /** 查询测试单表列表 */
    getList() {
      this.loading = true
      // this.queryParams.modelId = this.modelId[2]?.id
      getCarModelList(this.queryParams).then((res) => {
        if (res.code == '200') {
          const { rows, total } = res
          this.dataList = rows
          this.total = total
          this.loading = false
        }
      })
    },
    getListDig() {
      this.loadingDig = true
      getListDig(this.queryParamsDig).then((res) => {
        if (res.code == '200') {
          const { rows, total } = res
          this.dataListDig = rows
          this.totalDig = total
          this.loadingDig = false
        }
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
    },
    closeDig() {
      this.openDig = false
    },
    submitDig() {
      this.openDig = false
      this.modelNameDig = this.modelName
    },
    reset() {
      this.form = {}
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      //   if (this.modelId.length < 3) {
      //     return this.$message.error("请选择车型");
      //   } else {
      this.getList()
      //   }
    },

    /** 重置按钮操作 */
    resetQuery() {
      ;(this.queryParams = {
        pageNum: 1,
        pageSize: 10,
      }),
        (this.seriesList = [])
      this.carIdList = []
      this.handleQuery()
    },
    /** 新增操作 */
    handleAdd() {
      this.open = true
      this.title = '新增'
      this.$refs['form'] && this.$refs['form'].resetFields()
      this.modelNameDig = ''
      this.radio = ''
      this.reset()
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      console.log(row)
      this.open = true
      this.title = '编辑'
      carModelDetail(row.id).then((res) => {
        this.form = res.data
        this.modelNameDig = res.data.modelName
        this.radio = res.data.modelId
      })
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.form.modelId = this.radio
          this.form.liter = 1
          this.form.energyType = 1
          if (this.title == '新增') {
            carModelAdd(this.form).then((res) => {
              this.cancel()
              this.getList()
              this.$message.success('新增成功')
            })
          } else {
            // 调取接口
            carModelUpdate(this.form).then((res) => {
              this.cancel()
              this.getList()
              this.$message.success('编辑成功')
            })
          }
        }
      })
    },
  },
}
</script>

<style lang="scss" scoped>
.pagination-container {
  padding: 0 20px 50px !important;
}

.form-dialog {
  ::v-deep .el-dialog__header {
    padding: 10px 20px;
    border-bottom: 1px solid #dcdfe6;

    .el-dialog__headerbtn {
      top: 15px;
    }
  }

  .box-card {
    margin-bottom: 20px;

    .card-title {
      font-size: 16px;
      position: relative;
      margin-left: 8px;
      padding: 0;
    }

    .card-title::after {
      content: '';
      width: 4px;
      height: 18px;
      background-color: aqua;
      display: block;
      position: absolute;
      left: -12px;
      top: 2px;
    }
  }
}
</style>
